package cn.cxq.learning.e4;

public class Bisection {

    int MN = 51;
    int RN = 1;
    double ANS, ERR, EPS = 0.4E-14;
    double[] A = new double[MN];
    double[] B = new double[MN];
    double[] X = new double[MN];
    double[] Y = new double[MN];
    double[] E = new double[MN];

    private double f(double x) {
        return x * x * x - 2.0 * x - 2;
    }

    public double BISECTION(double A0, double B0) {

        double FA;
        int K;
        FA = f(A0);
        A[0] = A0;
        B[0] = B0;
        X[0] = (A0 + B0) / 2.0;
        Y[0] = f(X[0]);
        E[0] = (B0 - A0) / 2;
        for (K = 1; K < MN; K++) {
            if (Y[K - 1] * FA > 0) {
                A[K] = X[K - 1];
                B[K] = B[K - 1];
            } else {
                A[K] = A[K - 1];
                B[K] = X[K - 1];
            }
            X[K] = (A[K] + B[K]) / 2.0;
            Y[K] = f(X[K]);
            E[K] = (B[K] - A[K]) / 2;
            if (E[K] < EPS) {
                break;
            }
        }

        if (K < MN) K++;
        RN = K;
        ANS = X[RN - 1];
        ERR = E[RN - 1];
        System.out.print(String.format("%.15f ", A[K - 1]));
        System.out.print(String.format("%.15f ", B[K - 1]));
        return ANS;
    }
}
